// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContinuationSource.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the ContinuationSource type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Threading
{
    using System;
    using System.Collections.Generic;
    using System.Threading;

    // TODO: Verify primitive implementation
    public class ContinuationSource : IContinuationSource
    {
        #region Fields

        private readonly List<Action> _actions;
        private volatile int _isCompleted;

        #endregion

        public ContinuationSource()
        {
            _actions = new List<Action>();
        }

        protected void Completed()
        {
            if (_isCompleted == 0)
            {
#pragma warning disable 420
                if (Interlocked.CompareExchange(ref _isCompleted, 1, 0) == 0)
                {
                    InvokeActions();
                }
#pragma warning restore 420
            }
        }

        protected bool IsComplete
        {
            get
            {
                return _isCompleted == 1;
            }
        }

        public void ContinueWith(Action action)
        {
            // add action
            lock (_actions)
                _actions.Add(action);

            // may have completed in mean time
            if (_isCompleted == 1)
            {
                InvokeActions();
            }
        }

        private void InvokeActions()
        {
            lock (_actions)
            {
                while (_actions.Count > 0)
                {
                    _actions[0]();
                    _actions.RemoveAt(0);
                }
            }
        }
    }
}